using UnityEngine;
using UnityEditor;
using System.IO;
using UnityEngine.U2D;
using UnityEditor.U2D;

public class SpriteAtlasPackerTool : Editor
{
    private const string AtlasSavePath = "Assets/Arts/SpriteAtlas"; // 固定保存路径

    [MenuItem("Assets/打包到图集", false, 1)] // 添加右键菜单
    private static void PackSpritesToAtlas()
    {
        // 获取选中的文件夹路径
        string folderPath = AssetDatabase.GetAssetPath(Selection.activeObject);
        if (string.IsNullOrEmpty(folderPath) || !AssetDatabase.IsValidFolder(folderPath))
        {
            Debug.LogError("请选择一个有效的文件夹！");
            return;
        }

        // 获取文件夹中的所有图片
        string[] filePaths = Directory.GetFiles(folderPath, "*.*", SearchOption.AllDirectories);
        var textures = new System.Collections.Generic.List<Texture2D>();

        foreach (string file in filePaths)
        {
            if (file.EndsWith(".png") || file.EndsWith(".jpg"))
            {
                Texture2D texture = AssetDatabase.LoadAssetAtPath<Texture2D>(file.Replace("\\", "/"));
                if (texture != null)
                {
                    textures.Add(texture);
                }
            }
        }

        if (textures.Count == 0)
        {
            Debug.LogError("文件夹中没有找到有效的图片资源！");
            return;
        }

        // 确保保存路径存在
        if (!Directory.Exists(AtlasSavePath))
        {
            Directory.CreateDirectory(AtlasSavePath);
            AssetDatabase.Refresh();
        }

        // 获取文件夹名称作为图集名称
        string folderName = Path.GetFileName(folderPath);
        string atlasPath = $"{AtlasSavePath}/{folderName}.spriteatlas";

        // 创建图集
        CreateSpriteAtlas(textures, atlasPath);
    }

    private static void CreateSpriteAtlas(System.Collections.Generic.List<Texture2D> textures, string atlasPath)
    {
        // 创建 Sprite Atlas 对象
        SpriteAtlas spriteAtlas = new SpriteAtlas();

        // 配置 Sprite Atlas 参数
        SpriteAtlasPackingSettings packingSettings = new SpriteAtlasPackingSettings
        {
            blockOffset = 2,             // 精灵之间的间距
            enableRotation = false,      // 不允许旋转
            enableTightPacking = false   // 不启用紧密打包
        };
        spriteAtlas.SetPackingSettings(packingSettings);

        SpriteAtlasTextureSettings textureSettings = new SpriteAtlasTextureSettings
        {
            readable = false,           // 运行时不可读
            generateMipMaps = false,    // 不生成 MipMaps
            sRGB = true                 // 使用 sRGB 颜色空间
        };
        spriteAtlas.SetTextureSettings(textureSettings);

        // 添加图片到 SpriteAtlas
        foreach (var texture in textures)
        {
            string assetPath = AssetDatabase.GetAssetPath(texture);
            Object asset = AssetDatabase.LoadAssetAtPath<Object>(assetPath);
            spriteAtlas.Add(new[] { asset });
        }

        // 保存 Sprite Atlas 到指定路径
        AssetDatabase.CreateAsset(spriteAtlas, atlasPath);
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();

        Debug.Log($"图集打包完成！保存路径：{atlasPath}");
    }
}
